﻿using System.Security.Claims;
using BPM.Web.Shared.Data;
using BPM.Web.Shared.Auth;
using Microsoft.AspNetCore.Components.Authorization;
using BPM.Web.Shared.Dependencies;
using BootstrapBlazor.Components;
using Microsoft.AspNetCore.Components.Routing;
using BPM.Web.Shared.Extensions;
using Microsoft.AspNetCore.Components;

namespace BPM.Web.Shared.Service;

/// <summary>
/// 登录服务
/// </summary>
[Scoped(typeof(ISysAuthService))]
public class SysAuthService : BaseService, ISysAuthService
{
    private readonly IAuthClient _client;

    public SysAuthService(IAuthClient client, ToastService toast) : base(toast)
        => _client = client;

    /// <summary>
    /// 登录验证
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task<XnRestfulResult<string>> LoginAsync(LoginInput input)
        => await _client.LoginAsync(input);

    /// <summary>
    /// 获取用户信息
    /// </summary>
    /// <returns></returns>
    public Task<LoginOutput?> GetLoginUserAsync() => QueryAsync(_client.GetLoginUserAsync());

    /// <summary>
    /// 获取应用和菜单信息
    /// </summary>
    /// <returns></returns>
    public async Task<(IEnumerable<MenuItem>, IEnumerable<MenuItem>)> GetLoginUserDataAsync()
    {
        var apps = Enumerable.Empty<MenuItem>();
        var menus = Enumerable.Empty<MenuItem>();
        var result = await QueryAsync(_client.GetLoginUserAsync());
        if (result != null)
        {
            if (result.Apps.HasValue())
            {
                apps = result.Apps
                    .BuildNodeItem((x, r) =>
                    {
                        r.Id = x.Code ?? x.Id.ToString();
                        r.Icon = "fa fa-tasks fa-fw";
                        r.Text = x.Name ?? string.Empty;
                        r.IsActive = x.Active == "Y";
                    });
            }

            if (result.Menus.HasValue())
            {
                menus = result.Menus
                    .BuildTreeNode()
                    .BuildMenuItem<AntDesignTreeNode, long>((x, r) =>
                    {
                        r.Id = x.Id.ToString();
                        r.Icon = x.Meta.Icon;
                        r.Text = x.Meta.Title;
                        r.Target = x.Meta.Target;
                        r.Url = x.Path;
                        r.Match = NavLinkMatch.All;
                    });
            }
        }

        return (apps, menus);
    }

    /// <summary>
    /// 注销登录
    /// </summary>
    /// <returns></returns>
    public async Task LogoutAsync() => await _client.LogoutAsync();
}

